import { codeMsg } from "@/apis/user"
import type { CodeType } from "@/types/user"
import { showToast, type FormInstance } from "vant"
import { onUpdated, ref, type Ref } from "vue"
const formTel = ref<FormInstance>()
export const useMobileCode =(mobile:Ref<string>,type:CodeType='login')=>{
  //发送短信验证码
const time = ref(0)
let timer: number
const onSend= async () => {
  //已经倒计时time的值大于0，此时不能发送验证码
  if (time.value > 0) return
  //手机号校验
  await formTel.value?.validate('mobile')
  //获取手机验证码
  const res = await codeMsg(mobile.value, type)
  console.log(res.data.code)
  showToast({
    duration: 700,
    message: res.data.code,
  })
  //处理倒计时
  time.value = 60
  //定义定时器
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    time.value--
    if (time.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)

}

onUpdated(() => {
  //清除定时器
  clearInterval(timer)
})

return {
  onSend,
  time,
  formTel
}
}